#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<assert.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;

int main()
{
    //创建管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    assert(n != -1);
    (void)n;

    //创建子进程
    pid_t id = fork();
    assert(id != -1);
    if(id == 0)
    {
        //子进程 - 读
        close(pipefd[1]);
        //将数据读取到buff里,并打印
        char buff[1024];
        while(true)
        {
            ssize_t s = read(pipefd[0],buff,sizeof(buff)-1);
            if(s > 0)
            {
                cout<<"Father:"<<buff<<endl;
            }
        }
        exit(0);

    }
    //父进程 - 写
    close(pipefd[0]);
    string message = "我是父进程,我正在发送消息";
    int count = 0;
    char send_buff[1024];

    while(true)
    {
        //往send_buff里面写要发送的信息
        snprintf(send_buff,sizeof(send_buff),"%s[%d]:%d",message.c_str(),getpid(),count++);
        //写入管道
        write(pipefd[1],send_buff,strlen(send_buff));
        sleep(1);
    }

    pid_t ret = waitpid(id,nullptr,0);
    assert(ret > 0);
    (void)ret;

    return 0;
}
